import os
import sys
from PySide6.QtCore import (Slot)
from PySide6.QtWidgets import (
    QDialog
    ,QListWidget
    ,QListWidgetItem
    ,QTextEdit
    ,QPushButton
    ,QLabel
    )
from PySide6.QtUiTools import QUiLoader
import pandas as pd
from GuidsSync import GuidsSync,GuidDescr
import time

class GuidsWindowOld(QDialog):
    
    normalButtonColor="background-color: rgb(236, 236, 236);"
    warningButtonColor = "background-color: rgb(255, 179, 48);"
    
    guids={}
    
    def __init__(self, guidsDir:str, syncModule:GuidsSync=None) -> None:
        super().__init__()
        loader = QUiLoader()
        self.local_dir = guidsDir
        self.remote_dir = None
        self.sync_module = syncModule
        try:
            if not os.path.isdir(guidsDir): raise Exception(f"Директория справочников '{guidsDir}' отсутсвует.")
            self.files = [f for f in os.listdir(guidsDir) if "~$" not in f and ".xlsx" in f]
            for file in self.files:
                fullName = f"{guidsDir}\\{file}"
                key = file.replace(".xlsx","")
                self.guids[key]=fullName
            try:
                self.cur_path = sys._MEIPASS
            except:
                self.cur_path = os.path.dirname(os.path.realpath(__file__))
            
            self.GuidsDialog:QDialog = loader.load(f"{self.cur_path}\\GuidsWindowOld.ui", None)
            self.guidsList:QListWidget = self.GuidsDialog.guidsList
            self.textGuid:QTextEdit = self.GuidsDialog.textGuid
            self.remoteGuidsButton:QPushButton = self.GuidsDialog.remoteGuidsButton
            self.localGuidsButton:QPushButton = self.GuidsDialog.localGuidsButton
            self.syncWarningLabel:QLabel = self.GuidsDialog.syncWarningLabel
            self.reload_guids_list()
            self.guidsList.itemSelectionChanged.connect(self.list_item_selected)
            self.guidsList.itemDoubleClicked.connect(self.list_item_dbl_click)
            self.remoteGuidsButton.clicked.connect(self.remote_guids_button_clicked)
            self.localGuidsButton.clicked.connect(self.local_guids_button_clicked)
            self.check_guids_modified()
        except : raise
        
    def show(self):
        self.GuidsDialog.exec()
        
    def check_guids_modified(self):
        try:
            if self.sync_module is None: 
                self.remoteGuidsButton.setStyleSheet(self.normalButtonColor)
                self.localGuidsButton.setStyleSheet(self.normalButtonColor)
                self.remoteGuidsButton.setDisabled(True)
                self.localGuidsButton.setDisabled(True)
                # raise Exception("Модуль синхронизации справочников не инициализирован")
            else:
                self.syncWarningLabel.hide()
                check_result=self.sync_module.check()
                self.remoteGuidsButton.setStyleSheet(self.warningButtonColor if check_result[0] else self.normalButtonColor)
                self.localGuidsButton.setStyleSheet(self.warningButtonColor if check_result[1] else self.normalButtonColor)
            
        except: raise
        
    def reload_guids_list(self):
        """ Перезагрузка списка справочника """
        try:
            self.guidsList.addItems(self.guids.keys())
        except: raise
        
    @Slot()
    def list_item_selected(self):
        """ Обработчик выбора справочника из списка """
        try:
            list:QListWidget = self.sender()
            selected:QListWidgetItem = list.selectedItems()[0]
            key = selected.data(0)
            # print(key)
            df = pd.read_excel(self.guids[key])
            table=df.to_html(index=False,header=True,justify="center",na_rep="",decimal=",")
            html=f"""<html>
                <head>
                <style>
                table, th, td {{font-size:11pt; font-family: sans-serif; border:1px solid black; border-collapse:collapse; text-align:left;}}
                th, td {{padding: 3px;}}
                </style>
                </head>
                <body>{table}</body>
                </html>"""
            self.textGuid.setHtml(html)
        except: raise
        
    @Slot()
    def list_item_dbl_click(self):
        """ Обработчик двойного клика по названию справочника """
        list:QListWidget = self.sender()
        selected:QListWidgetItem = list.selectedItems()[0]
        key = selected.data(0)
        os.system(f'start EXCEL.exe "{self.guids[key]}"')
        self.sync_module.reconnect()
        self.check_guids_modified()
        
    def remote_guids_button_clicked(self):
        try:
            self.sync_module.get_from_remote()
            self.check_guids_modified()
            self.sync_module.send_to_remote()
            self.remoteGuidsButton.setStyleSheet(self.normalButtonColor)            
        except: raise
        
    def local_guids_button_clicked(self):
        try:
            self.sync_module.send_to_remote()
            self.localGuidsButton.setStyleSheet(self.normalButtonColor)
        except: raise